/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.seq.service  
 */
package com.apache.seq.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.apache.api.vo.ParamsVo;
import com.apache.database.constant.SpringContextLoader;
import com.apache.method.ThreadPool;
import com.apache.seq.entity.Seq;
import com.apache.seq.manager.SeqManager;

/**
 * description:  序列号辅助类
 * @author Hou Dayu 创建时间：2015-6-26  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
public class SeqHelperUtil {

	/**30位*/
	private static final String headStr = "000000000000000000000000000000";
	private static ThreadPool pool;

	/**
	 * description:  计算下一个序列号
	 * @param prefix 前缀
	 * @param start  开始值
	 * @param step   步长
	 * @param len    长度
	 * @return  下一个序列号
	 */
	public static String calculateNextSeq(String prefix, Seq seq, int len) {
		SimpleDateFormat yyMMTime = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = yyMMTime.format(new Date());
		boolean mark = seq.getLastGetTime().indexOf(dateStr) == -1;//判断是否为当天
		long start = 1;
		if (mark) {//若日期!=今日
			start = 1;
			seq.setNextValue(1l);
		}
		start = seq.getNextValue() == null ? 1L : seq.getNextValue().longValue();
		dateStr = dateStr.replaceAll("-", "");
		String value = start + "";
		String nextValue = "";
		if (len > 0) {
			int nvLen = value.length();
			if (nvLen < len) {
				int addLen = len - nvLen;
				nextValue = prefix + dateStr + headStr.substring(0, addLen) + value;
			}
		}
		if ("".equals(nextValue)) {
			nextValue = prefix + dateStr + value;
		}
		return nextValue;
	}

	/**
	 * description:  计算下一个序列号
	 * @param prefix 前缀
	 * @param start  开始值
	 * @param step   步长
	 * @param len    长度
	 * @return  下一个序列号
	 */
	public static String calculateNextSeq2(String prefix, long start, int len) {
		if (start < 1) {
			start = 1;
		}
		String nextValue = start + "";
		if (len > 0) {
			int nvLen = nextValue.length();
			if (nvLen < len) {
				int addLen = len - nvLen;
				nextValue = prefix + headStr.substring(0, addLen) + nextValue;
			}
		}
		if ("".equals(nextValue)) {
			nextValue = prefix + nextValue;
		}
		return nextValue;
	}

	public static void SeqThread(final Seq seq) {
		if (null == pool) {
			pool = new ThreadPool(1, "序列插入线程");
		}
		pool.execute(new Thread() {
			private Logger log = Logger.getLogger(SeqHelperUtil.class);

			public void run() {
				ParamsVo<Seq> pvo = new ParamsVo<Seq>();
				pvo.setObj(seq);
				SeqManager seqManager = (SeqManager) SpringContextLoader.getBean("seqManager");
				boolean mark = seqManager.editInfo(pvo);
				log.info("序列插入线程 seq:" + seq.toString() + "; 结果 mark=" + mark);
			};
		});
	}
}
